import java.util.*;
import java.io.*;

import com.sleepycat.*;

public class DateSeries {
	
	private ArrayList<String> dates;
	private BerkeleyDBWrapper wrapper;
	
	public DateSeries() throws FileNotFoundException{
		wrapper = new BerkeleyDBWrapper("./DB"); 
		dates = wrapper.getDBArrayListVal("dates");
	}
	
	public List<String> getDateSeries(String start, String end){
		end=getFirstDateBeforeStart(end);
		start=getFirstDateAfterEnd(start);
		int from= dates.lastIndexOf(start);
		int to= dates.lastIndexOf(end);
		if(from<to){
			to++;
			List<String> toReturn = dates.subList(from, to);
			return toReturn;
		}else{
			from++;
			List<String> toReturn = dates.subList(to, from);
			return toReturn;
		}
	}
	
	private String getFirstDateBeforeStart(String start){
		if (dates.contains(start)){
			return start;
		}
		int month = Integer.parseInt(start.substring(0, start.indexOf("/")));
		int day = Integer.parseInt(start.substring(start.indexOf("/")+1, start.lastIndexOf("/")));
		int year = Integer.parseInt(start.substring(start.lastIndexOf("/")+1, start.length()));
		if(day == 1){
			if(month ==1){
				month =12;
				year--;
				day = 31;
			}else{
				month--;
			}
			if (month == 4 || month == 6 || month == 9 || month == 11){
				day = 30;
			}else if (month == 2){
				if (year%4 == 0){
					day = 29;
				}else{
					day = 28;
				}
			}else{
				day = 31;
			}
		}else{
			day--;
		}
		String toReturn = Integer.toString(month)+"/"+Integer.toString(day)+"/"+Integer.toString(year);
		if (dates.contains(toReturn)){
			return toReturn;
		}else{
			return getFirstDateBeforeStart(toReturn);
		}
	}

	private String getFirstDateAfterEnd(String end){
		if (dates.contains(end)){
			return end;
		}
		int month = Integer.parseInt(end.substring(0, end.indexOf("/")));
		int day = Integer.parseInt(end.substring(end.indexOf("/")+1, end.lastIndexOf("/")));
		int year = Integer.parseInt(end.substring(end.lastIndexOf("/")+1, end.length()));
		if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 30){ 
			month = month++;
			day = 1;
		}else if (month == 2){
			if (year%4 == 0){
				if (day == 29){
					month = 3;
					day = 1;
				}
			}else{
				if (day == 28){
					month =3;
					day = 1;
				}
			}
		}else if (day == 31){
			if (month !=12){
				month++;
				day = 1;
			}else{
				month = 1;
				day = 1;
				year++;
			}
		}else{
			day++;
		}
		String toReturn = Integer.toString(month)+"/"+Integer.toString(day)+"/"+Integer.toString(year);
		if (dates.contains(toReturn)){
			return toReturn;
		}else{
			return getFirstDateAfterEnd(toReturn);
		}
	}
}
